package lt.marsrutai.mobile.android.activity;

import java.util.List;
import java.util.Map.Entry;

import lt.marsrutai.mobile.android.AppContext;
import lt.marsrutai.mobile.android.R;
import lt.marsrutai.mobile.android.activity.intent.SchedulesIntentHolder;
import lt.marsrutai.mobile.android.activity.intent.StopTimesIntentHolder;
import lt.marsrutai.mobile.android.activity.intent.StopsIntentHolder;
import lt.marsrutai.mobile.android.activity.intent.TracksIntentHolder;
import lt.marsrutai.mobile.android.adapter.StopTimesTabInfoProvider;
import lt.marsrutai.mobile.android.adapter.TabAdapter;
import lt.marsrutai.mobile.android.exception.DataAccessException;
import lt.marsrutai.mobile.android.fragment.StopTimesFragment;
import lt.marsrutai.mobile.android.manager.ActivityManager;
import lt.marsrutai.mobile.android.model.ArrivalTime;
import lt.marsrutai.mobile.android.model.DayGroup;
import lt.marsrutai.mobile.android.model.StopArrivalTimes;
import lt.marsrutai.mobile.android.model.enums.DateTime;
import lt.marsrutai.mobile.android.model.enums.WeekdayType;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;

import com.viewpagerindicator.TabPageIndicator;

public class StopTimesActivity extends BaseActivity {

    private ActivityManager manager;
    private StopArrivalTimes stopArrivalTimes;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        manager = new ActivityManager(this);

        // Display loading in the temp view while the data is downloading
        setContentView(R.layout.progress_spinner);
        manager.showDownloadLoadingBar();

        downloadData();
    }

    @Override
    public boolean onNavigationItemSelected(int itemPosition, long itemId) {
        StopTimesIntentHolder sourceIntentHolder = new StopTimesIntentHolder(getIntent());

        switch (itemPosition) {
        case 1:
            StopsIntentHolder stopsintentHolder = new StopsIntentHolder(this,
                sourceIntentHolder.getScopeFolder(),
                sourceIntentHolder.getScopeName(),
                sourceIntentHolder.getTransportId(),
                sourceIntentHolder.getScheduleId(),
                sourceIntentHolder.getScheduleName(),
                sourceIntentHolder.getScheduleTrackName(),
                sourceIntentHolder.getTrackId(),
                sourceIntentHolder.getTrackName()
            );
            startActivity(stopsintentHolder.getIntent());
            break;
        case 2:
            TracksIntentHolder tracksintentHolder = new TracksIntentHolder(this,
                sourceIntentHolder.getScopeFolder(),
                sourceIntentHolder.getScopeName(),
                sourceIntentHolder.getTransportId(),
                sourceIntentHolder.getScheduleId(),
                sourceIntentHolder.getScheduleName(),
                sourceIntentHolder.getScheduleTrackName()
            );
            startActivity(tracksintentHolder.getIntent());
            break;
        case 3:
            SchedulesIntentHolder schedulesIntentHolder = new SchedulesIntentHolder(this);
            schedulesIntentHolder.setScopeFolder(sourceIntentHolder.getScopeFolder());
            schedulesIntentHolder.setScopeName(sourceIntentHolder.getScopeName());
            startActivity(schedulesIntentHolder.getIntent());
            break;
        case 4:
            startActivity(new Intent(this, ScopesActivity.class));
            break;
        default:
            return false;
        }

        return false;
    }

    @Override
    public NavMenuData getNavMenuData() {
        StopTimesIntentHolder intentHolder = new StopTimesIntentHolder(getIntent());
        return new NavMenuData(new String[] {
                intentHolder.getStopName() + (intentHolder.getStopDirectionName() == null ? "" :  " (" + intentHolder.getStopDirectionName() + ")"),
                intentHolder.getTrackName(), 
                intentHolder.getScheduleTrackName(),
                intentHolder.getScopeName(), 
                getString(R.string.home) 
                },
                intentHolder.getScheduleName(), 2, intentHolder.getScopeFolder(), intentHolder.getTransportId());
    }

    private void initialize() {
        TabAdapter adapter = new TabAdapter(getSupportFragmentManager());
        WeekdayType today = WeekdayType.parseEnumSunSat(new DateTime().getWeekDay());
        int currentTabIndex = 0;
        int index = 0;

        for (Entry<DayGroup, List<ArrivalTime>> entry : stopArrivalTimes.getArrivalTimes()) {
            DayGroup dayGroup = entry.getKey();

            // Fill intent holder with proper info
            StopTimesIntentHolder intentHolder = new StopTimesIntentHolder(getIntent().getExtras());
            intentHolder.setArrivalTimes(entry.getValue());

            // Add the tab
            adapter.addTab(new StopTimesTabInfoProvider(StopTimesFragment.class, intentHolder.getIntent().getExtras(), this, dayGroup));

            // Store the position of the current tab
            if (dayGroup.contains(today)) {
                currentTabIndex = index;
            }

            index++;
        }

        // Attach the adapted to the view pager
        setContentView(R.layout.tabs_viewpager_layout);
        ViewPager pager = (ViewPager) findViewById(R.id.viewpager);
        pager.setAdapter(adapter);

        // Attach view pager to tab page indicator
        TabPageIndicator indicator = (TabPageIndicator) findViewById(R.id.indicator);
        indicator.setViewPager(pager);

        pager.setCurrentItem(currentTabIndex);
    }

    private void downloadData() {
        Runnable downloadTask = new Runnable() {

            @Override
            public void run() {
                try {
                    StopTimesIntentHolder intentHolder = new StopTimesIntentHolder(getIntent().getExtras());
                    String scopeFolder = intentHolder.getScopeFolder();
                    String scheduleId = intentHolder.getScheduleId();
                    String trackId = intentHolder.getTrackId();
                    String stopId = intentHolder.getStopId();
                    stopArrivalTimes = AppContext.getDataService().getStopTimes(scopeFolder, scheduleId, trackId, stopId);
                }
                catch (DataAccessException e) {
                    manager.runOnUiThread(manager.errorRes);
                    return;
                }
                manager.runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        initialize();
                    }
                });
            }
        };
        Thread thread = new Thread(downloadTask);
        thread.start();
    }
}
